﻿namespace Digitalmes.WebApi.Endpoints;

/// <summary>
/// Server Sent Events。
/// </summary>
public sealed class SseEndpoint : EndpointGroupBase
{
    public override void Map(WebApplication app)
    {
        app.MapGroup(this)
            .MapGet(Sse);
    }

    public async Task Sse(HttpContext context, IMessageQueue<PushMessageData> broker, CancellationToken cancellationToken)
    {
        context.Response.Headers.Append("Content-Type", "text/event-stream");
        context.Response.Headers.Append("Cache-Control", "no-cache");
        context.Response.Headers.Append("Connection", "keep-alive");
        context.Response.Headers.Append("Access-Control-Allow-Origin", "*");

        // JavaScript
        // const source = new EventSource('http://localhost:5000/api/sse');
        // source.onmessage = function(e) {
        //     const item = JSON.parse(e.data);
        //     console.log(e.data);
        // };

        // while read channel data...
        while (!cancellationToken.IsCancellationRequested)
        {
            var message = await broker.DequeueAsync(cancellationToken);

            StringBuilder sb = new();
            sb.AppendFormat("id: {0}\n", Guid.NewGuid())
                .Append("event: message\n")
                .Append("retry: 10000\n")
                .AppendFormat("data: {0}\n", message.ToJson())
                .Append("\n\n"); // 两条消息之间有一个空行

            await context.Response.WriteAsync(sb.ToString());
            await context.Response.Body.FlushAsync();
        }
    }
}
